<template>
	<div class="layout-padding" v-loading="printing">
		<div class="layout-padding-auto layout-padding-view" style="overflow: auto">
			<el-row v-show="showSearch" style="width: 100%; text-align: right">
				<div style="font-size: 18px; font-weight: 700">年度项目概览</div>
				<el-form :model="queryForm" ref="queryRef" :inline="true" @keyup.enter="getDataList" style="width: 100%">
					<el-form-item label="年份" prop="name">
						<el-select v-model="queryForm.year" placeholder="请选择年份" @change="getDataList">
							<el-option :key="index" :label="item" :value="item" v-for="(item, index) in yearData" />
						</el-select>
					</el-form-item>
				</el-form>
			</el-row>
			<el-row class="w-full">
				<div ref="captureRef" class="w-full">
					<!-- <el-checkbox class="pr-2"></el-checkbox> -->
					<project-info
						class="project-info"
						:class="item.selected ? 'printing' : ''"
						:project-info="item"
						:year="queryForm.year"
						:is-print="printing"
						:key="index"
						v-for="(item, index) in projectList"
					></project-info>
				</div>
			</el-row>
			<el-row>
				<div class="mb8" style="width: 100%; text-align: right">
					<el-button type="primary" class="m-10" @click="handlePrint">打印</el-button>
				</div>
			</el-row>
		</div>
		<!-- 隐藏的打印容器 -->
		<div id="printContainer" class="only-print">
			<img :src="item" class="print-image" :key="index" v-for="(item, index) in imageUrls" />
		</div>
	</div>
</template>

<script setup lang="ts" name="internalOverviewAnalysis">
import html2canvas from 'html2canvas';
import printJS from 'print-js';
import { getOverviewData as overviewAnalysis } from '/@/api/internal/cost/intProjectAnalysis';
// 引入组件
const ProjectInfo = defineAsyncComponent(() => import('./components/projectInfo.vue'));

const showSearch = ref(true);
// const loading = ref(true); // 表格遮罩层
const printing = ref(false); // 表格遮罩层

const getAllYears = (startYear: number, endYear: number) => {
	const years: number[] = [];
	for (let year = startYear; year <= endYear; year++) {
		years.push(year);
	}
	return years;
};

// 定义变量内容=
const yearData = getAllYears(2024, new Date().getFullYear()); // 年度列表

const projectList = ref([]);

// 查询参数
const queryForm = reactive({
	year: new Date().getFullYear(),
});

// 获取成本项分析数据
const getDataList = async () => {
	overviewAnalysis(queryForm).then((res) => {
		projectList.value = res.data;
	});
};
getDataList();

// 元素引用
const captureRef = ref<HTMLElement | null>(null);
const imageUrls = ref<string[]>([]);

const generatePrintImage = async () => {
	// 配置选项（可选）
	const options: html2canvas.Options = {
		scale: 4, // 缩放比例
		useCORS: true, // 允许跨域图片
		logging: true, // 调试日志
		backgroundColor: '#FFFFFF',
	};
	imageUrls.value.length = 0;

	try {
		const printings = document.getElementsByClassName('printing');
		if (!printings || printings.length == 0) {
			const projectInfos = document.getElementsByClassName('project-info');
			projectInfos.forEach((item) => {
				html2canvas(item, options).then((canvas1) => {
					let dataURL = canvas1.toDataURL('image/png');
					imageUrls.value.push(dataURL);
				});
			});
		} else {
			printings.forEach((item) => {
				html2canvas(item, options).then((canvas1) => {
					let dataURL = canvas1.toDataURL('image/png');
					imageUrls.value.push(dataURL);
				});
			});
		}
	} catch (error) {
		console.error('截图失败:', error);
	}
};
const handlePrint = () => {
	printing.value = true;
	nextTick(() => {
		generatePrintImage();
		setTimeout(() => {
			printing.value = false;
			printJS({
				printable: imageUrls.value.map((img) => img), // 提取 URL 数组
				type: 'image',
				header: '',
				style: '@media print { body { margin: 0; } #printSection { margin-top: 0; } img { max-width: 100%; page-break-inside: avoid; } }', // 内联CSS样式
				imageStyle: 'width: 100%; margin: 10px auto; page-break-after: always;', // 分页关键
			});
		}, 5000);
	});
};
</script>
<style scoped>
/* 隐藏打印容器的优化方案 */
.only-print {
	display: none;
}

/* 打印时的图片样式 */
@media print {
	.print-image {
		width: 100% !important;
		height: auto !important;
		page-break-after: always; /* 分页控制（可选） */
	}
	.only-print {
		display: block !important; /* 显示仅在打印时可见的内容 */
	}
	@page {
		margin: 10px; /* 去除页边距 */
	}
}
</style>
